package com.gexiaobao.pigeon.ui.activity

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.bin.david.form.core.SmartTable
import com.bin.david.form.core.TableConfig
import com.bin.david.form.data.CellInfo
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat
import com.bin.david.form.data.style.FontStyle
import com.bin.david.form.data.style.LineStyle
import com.bin.david.form.data.table.MapTableData
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.RankListResponse
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.ActivityRaceRankingBinding
import com.gexiaobao.pigeon.ui.race.RaceViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.jessyan.autosize.internal.CustomAdapt
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.ceil

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 10:30
 * @Describe    : 比赛综合排名
 */
class ActivityRaceRanking : BaseActivity<RaceViewModel, ActivityRaceRankingBinding>(), CustomAdapt {

    private var landScreenBoolean = false
    private var landScreenFloat: Float = 580.0F
    private var landScreenFloatHW: Float = 420.0F
    private var landScreenFloatNok: Float = 410.0F
    private var landScreenFloatS: Float = 760.0F

    private var pageNo = 1
    private var pageSize = "50"
    private var pageSizeAll = "2000000"
    private var totalPage = 0
    private var raceId = ""
    private var mFosterName = ""
    private var ringId = ""
    private var memberCode = ""//获取棚号
    lateinit var data: SmartTable<RankListResponse>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        StatusBarUtil.setLightMode(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarTranslucent()
        mDatabind.etSearch.hint = getString(R.string.Enter_the_pigeon_owner_name)
        mDatabind.viewmodel = mViewModel
        mViewModel.rankingTitle.set(intent.getStringExtra("title"))
        raceId = intent.getIntExtra("raceId", 0).toString()
        initSmartTable()

        showLoading(getString(R.string.loading))
        mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, "", "", "", "")

        mDatabind.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchResult()

                else -> {}
            }
            false
        }
        mDatabind.etSearch.addTextChangedListener {
            if (it?.isEmpty() == true) {
                pageNo = 1
                memberCode = ""
                mFosterName = ""
                showLoading(getString(R.string.loading))
                mViewModel.getRaceResult(
                    pageSizeAll,
                    pageNo.toString(),
                    raceId,
                    memberCode,
                    ringId,
                    mFosterName,
                    mViewModel.etSearchContent.get()
                )
            }
        }
    }

    private fun searchResult() {
        hideSoftKeyboard(this)
        when {
            mViewModel.etSearchContent.get().isEmpty() -> showMessage(getString(R.string.Enter_what_you_want_to_query))
            else -> {
                pageNo = 1
                memberCode = ""
                mFosterName = ""
                showLoading(getString(R.string.loading))
                mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, memberCode, ringId, mFosterName, mViewModel.etSearchContent.get())
            }
        }
    }

    private fun initSmartTable() {
        data = mDatabind.smartTable as SmartTable<RankListResponse>
        val fontStyle = FontStyle(this, 19, ContextCompat.getColor(this, R.color.black))
        val contentStyle = FontStyle(this, 17, ContextCompat.getColor(this, R.color.comm_text_gray))
        val lineStyle = LineStyle()
        lineStyle.color = ContextCompat.getColor(this, R.color.dedede)
        data.config.columnTitleStyle = fontStyle
        data.config.contentStyle = contentStyle
        data.config.setHorizontalPadding(20)
            .setVerticalPadding(15)
            .setSequenceHorizontalPadding(20)
            .setSequenceVerticalPadding(40)
            .setShowTableTitle(false) // 去除标题
            .setFixedFirstColumn(true) //第一行作废
            .setShowXSequence(false)
            .setShowYSequence(false)
            .isFixedYSequence = true
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        mViewModel.totalRankResult.observe(this) {
            if (it != null) {
                val data = Gson().toJson(it)
                val result = JSONObject(data.toString())
                val passResultHead = result.getJSONArray("passResultHead")
                val passResultBody = result.getJSONArray("passResultBody")

                mDatabind.tvBackCount.text = getString(R.string.back) + result.getInt("total") + getString(R.string.yu)
                if (passResultBody.length() == 0) {
                    mViewModel.totalPage.set("1/1")
                    mDatabind.smartTable.visibility = View.GONE
                    mDatabind.tvNoData.visibility = View.VISIBLE
                    RxToast.showToast(getString(R.string.No_comprehensive_score_was_generated))
                } else {
                    mDatabind.smartTable.visibility = View.VISIBLE
                    mDatabind.tvNoData.visibility = View.GONE
                    totalPage = ceil(SettingUtil.div(result.getInt("total").toDouble(), 50.00, 2)).toInt()//取整
                    setSmartTableData(passResultHead, passResultBody)
                }
                mViewModel.totalPage.set("$pageNo/$totalPage")
            }
        }

        mViewModel.memberNumResult.observe(this) {
            if (it != null) {
                pageNo = 1
                mFosterName = ""
                memberCode = it.memberNum
                mViewModel.etSearchContent.set("")
                showLoading(getString(R.string.loading))
                mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, memberCode, ringId, mFosterName, mViewModel.etSearchContent.get())
            }
        }
    }

    private fun setSmartTableData(passResultHead: JSONArray, passResultBody: JSONArray) {
        val list1 = ArrayList<Any>()
        var value = ""
        for (i in 0 until passResultBody.length()) {
            val map = LinkedHashMap<String, String>()
            for (j in 0 until passResultHead.length()) {
                val dataHead = passResultHead[j].toString()
                val dataBody = passResultBody[i].toString()
                val key = JSONObject(dataHead).getString("title")
                val valueStr = JSONObject(dataHead).getString("key")
                value = JSONObject(dataBody).getString(valueStr)
                if ("ringId" == valueStr) {
                    value = Util.check2FormatRingId(value)
                } else if ("homingTime" == valueStr || "lonLat" == valueStr) {
                    value = value.replace(" ", "\n")
                }
                map[key] = value
            }
            list1.add(map)
        }
        val mapData = MapTableData.create(getString(R.string.competition_results), list1)
        mapData.columns[0].isFixed = true
        mapData.columns[1].isFixed = true
        mapData.columns[3].isFixed = true
        mDatabind.smartTable.tableData = mapData

        data.config.contentCellBackgroundFormat = object : BaseCellBackgroundFormat<CellInfo<*>>() {
            override fun getBackGroundColor(t: CellInfo<*>): Int {
                return when (t.column.columnName) {
                    "特比1000" -> {
                        ContextCompat.getColor(this@ActivityRaceRanking, R.color.color_FFDAB9)
                    }

                    "特比100" -> {
                        ContextCompat.getColor(this@ActivityRaceRanking, R.color.color_FFEC8B)
                    }

                    else -> {
                        TableConfig.INVALID_COLOR
                    }
                }
            }

            override fun getTextColor(t: CellInfo<*>): Int {
                return when (t.column.columnName) {
                    "寄养人" -> {
                        ContextCompat.getColor(appContext, R.color.bg_light_bllue)
                    }

                    "棚号" -> {
                        ContextCompat.getColor(appContext, R.color.rnsn_color)
                    }

                    else -> {
                        super.getTextColor(t)
                    }
                }
            }
        }

        data.tableData?.setOnItemClickListener { column, value, t, col, row ->
            if ("寄养人" == column.columnName) {
                if (t != null) {
                    if (!TextUtils.isEmpty(t.toString())) {
                        mFosterName = value
                        pageNo = 1
                        memberCode = ""
                        mViewModel.etSearchContent.set(mFosterName)
                        showLoading(getString(R.string.loading))
                        mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, memberCode, "", mFosterName, mViewModel.etSearchContent.get())
                    }
                }
            }
            if ("棚号" == column.columnName) {
                if (t != null) {
                    if (!TextUtils.isEmpty(t.toString())) {
                        mFosterName = ""
                        pageNo = 1
                        memberCode = value
                        mViewModel.etSearchContent.set(memberCode)
                        showLoading(getString(R.string.loading))
                        mViewModel.getRaceResult(
                            pageSize,
                            pageNo.toString(),
                            raceId,
                            memberCode,
                            "",
                            mFosterName,
                            mViewModel.etSearchContent.get()
                        )
                    }
                }
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivMatchResultBack,
            mDatabind.tvMatchResultTitle,
            mDatabind.tvRaceRankResultPageAll,
            mDatabind.tvRaceRankResultPageMine,
            mDatabind.tvRaceRankResultPageRefresh,
            mDatabind.tvRaceRankResultPageFirst,
            mDatabind.tvRaceRankResultPageBefore,
            mDatabind.tvRaceRankResultPageNext,
            mDatabind.tvRaceRankResultPageLast
        ) {
            when (it) {
                mDatabind.ivMatchResultBack, mDatabind.tvMatchResultTitle -> {
                    finish()
                }

                mDatabind.tvRaceRankResultPageAll -> {
                    pageNo = 1
                    memberCode = ""
                    mFosterName = ""
                    mViewModel.etSearchContent.set("")
                    showLoading(getString(R.string.loading))
                    mViewModel.getRaceResult(
                        pageSizeAll,
                        pageNo.toString(),
                        raceId,
                        memberCode,
                        ringId,
                        mFosterName,
                        mViewModel.etSearchContent.get()
                    )
                }

                mDatabind.tvRaceRankResultPageMine -> {//本人
                    pageNo = 1
                    showLoading(getString(R.string.loading))
                    mViewModel.getRaceMemberNum(raceId)
                }

                mDatabind.tvRaceRankResultPageRefresh -> {
                    showLoading(getString(R.string.loading))
                    mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, memberCode, ringId, mFosterName, mViewModel.etSearchContent.get())
                }

                mDatabind.tvRaceRankResultPageFirst -> {//首页
                    if (pageNo == 1) {
                        RxToast.showToast(getString(R.string.page_one))
                        return@setOnclickNoRepeat
                    }
                    pageNo = 1
                    showLoading(getString(R.string.loading))
                    mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, memberCode, ringId, mFosterName, mViewModel.etSearchContent.get())
                }

                mDatabind.tvRaceRankResultPageBefore -> {//上一页
                    if (pageNo == 1) {
                        RxToast.showToast(getString(R.string.page_one))
                        return@setOnclickNoRepeat
                    }
                    pageNo--
                    showLoading(getString(R.string.loading))
                    mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, memberCode, ringId, mFosterName, mViewModel.etSearchContent.get())
                }

                mDatabind.tvRaceRankResultPageNext -> { //下一页
                    if (pageNo == totalPage) {
                        RxToast.showToast(getString(R.string.page_last))
                        return@setOnclickNoRepeat
                    }
                    pageNo++
                    showLoading(getString(R.string.loading))
                    mViewModel.getRaceResult(pageSize, pageNo.toString(), raceId, memberCode, ringId, mFosterName, mViewModel.etSearchContent.get())
                }

                mDatabind.tvRaceRankResultPageLast -> {//尾页
                    if (pageNo == totalPage) {
                        RxToast.showToast(getString(R.string.page_last))
                        return@setOnclickNoRepeat
                    }
                    pageNo = totalPage
                    showLoading(getString(R.string.loading))
                    mViewModel.getRaceResult(
                        pageSize,
                        totalPage.toString(),
                        raceId,
                        memberCode,
                        ringId,
                        mFosterName,
                        mViewModel.etSearchContent.get()
                    )
                }
            }
        }
    }

    override fun isBaseOnWidth(): Boolean {
        return if (Build.MANUFACTURER == "realme" || Build.MANUFACTURER == "vivo" || Build.MANUFACTURER == "OPPO"
            || Build.MANUFACTURER == "HUAWEI" || Build.MANUFACTURER == "HMD Global"
        ) {
            landScreenBoolean
        } else {
            !landScreenBoolean
        }
    }

    override fun getSizeInDp(): Float {
        return when (Build.MANUFACTURER) {
            "realme", "vivo", "OPPO" -> {
                landScreenFloat
            }

            "HUAWEI" -> {
                landScreenFloatHW
            }

            "HMD Global" -> {
                landScreenFloatNok
            }

            else -> {
                landScreenFloatS
            }
        }
    }

}